import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getAdminToken, getUserToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:8081/test', // url = base url + request url
  withCredentials: true, // 当跨域请求时发送cookie
  timeout: 5000 // request timeout
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // 发送请求之前做些什么
    // if (store.getters.token) {
    //   // let each request carry token
    //   // ['X-Token'] is a custom headers key
    //   // please modify it according to the actual situation
    //   config.headers['Admin-Token'] = getAdminToken()
    // } else {
    //   if (store.getters.user_token) {
    //     config.headers['User-Token'] = getUserToken()
    //   }
    // }
    // var token = getToken() // 第一个账号的token
    var href = window.location.href
    if (href.indexOf('/back') > -1) {
      config.headers['token'] = getAdminToken()
    } else {
      config.headers['token'] = getUserToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 相应拦截
service.interceptors.response.use(
  /**
   * 如果你想获得http标头或状态等信息
   * 请返回 response => response
  */

  /**
   * 确定自定义代码的请求状态
   * 这只是一个例子
   * 你也可以判断状态通过HTTP状态代码
   */
  response => {
    const res = response.data

    // 如果自定义代码不是1，则判断为错误。
    if (res.code !== 1) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: 非法令牌; 50012: Other clients logged in; 3: Token 过期;
      if (res.code === 50008 || res.code === 50012 || res.code === 13) {
        // to re-login
        MessageBox.confirm('用户名密码错误', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (store.getters.token) {
            store.dispatch('admin/resetToken').then(() => {
              location.reload()
            })
          } else if (store.getters.user_token) {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          }
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
